import PySimpleGUI as sg
from docxtpl import DocxTemplate
import configparser,os,datetime
import gonggao

context_Hetong = {}

class getConfig(object):
    def __init__(self,filename,context_Hetong):
        self.configObj = configparser.ConfigParser()
        try:
            self.configObj.read(filename)
            context_Hetong.setdefault('title',self.configObj['LAST']['title'])
        except:
            context_Hetong.setdefault('title','')

class Hetong(gonggao.gonggao):
    def __init__(self,context_Hetong):
        super().__init__(context_Hetong)

    def gethetong(self):
        document = DocxTemplate('采购合同模板.docx')
        document.render(self.context)
        document.save(os.path.join(self.GetDesktopPath(), '采购合同.docx'))
        return True,os.path.join(self.GetDesktopPath(), '采购合同.docx')

class GUI(sg.Window):
    def __init__(self,context_Hetong):
        super().__init__('自动生成工具')
        self.context = context_Hetong
        d = datetime.datetime.now()
        self.context.setdefault('today',str(d.year)+'年'+str(d.month)+'月'+str(d.day)+'日')
        print(self.context)
        self.texts = {'项目名称:':'title', '合同编号:':'number', '乙方公司:':'company', '法定代表人:':'legal_person', '乙方地址:':'company_adr'}
        layout1 = [
            [sg.Text(value,size=(10,1)),sg.Input(key=key,size=(31,1))] for value,key in self.texts.items()]
        sg.SetOptions(text_justification='center')
        headings = {'序号':4, '品名':12, '单位':4, '型号':12, '订货数量':8, '含税单价':10, '含税总价':10}
        header = [[sg.Text('  ')] + [sg.Text(h, size=(width, 1)) for h,width in headings.items()]]
        input_rows = [[sg.Text('  ')] +[sg.Input(size=(width+2, 1), pad=(1, 0)) for h,width in headings.items()] for row in range(3)]
        table_layout = header + input_rows
        layout2 = [[sg.Frame('货物清单：', table_layout, title_color='red'),]]
        self.payment_texts = {'付款比例':6,'付款条件':25}
        pay_header = [[sg.Text('  ')] + [sg.Text(h, size=(width, 1)) for h, width in self.payment_texts.items()]]
        pay_input_rows = [[sg.Text('  ')] +[sg.Input(size=(width+2, 1), pad=(1, 0)) for h,width in self.payment_texts.items()] for row in range(4)]
        frame_layout = [
            [sg.Text('请选择付款方式')],
            [sg.Radio('分4次付款',"RADIO1",default=True,key='payment4',enable_events=True),sg.Radio('分3次付款',"RADIO1",key='payment3',enable_events=True),
             sg.Radio('分2次付款',"RADIO1",key='payment2',enable_events=True),sg.Radio('一次性付款',"RADIO1",key='payment1',enable_events=True)],
        ] + pay_header + pay_input_rows
        layout3 = [[sg.Frame('付款方式，分几次付款：', frame_layout, title_color='red'),
                        sg.Text('质保期：', size=(10, 1)), sg.Input(key='period', default_text='1年', size=(10, 1))]]
        delivery_layout = [
            [sg.Text('交付时间：')],
            [sg.Radio('按天数计算：',"RADIO2",default=True,key='delivery1',size=(12,1)),sg.Input(key='delivery1_input')],
            [sg.Radio('具体交付时间：', "RADIO2", key='delivery2',size=(12,1)), sg.Input(key='delivery2_input',visible=False)],
            [sg.Text('交付地点：')],
            [sg.Radio('甲方所在地', "RADIO3", default=True, key='location1', size=(12, 1))],
            [sg.Radio('指定地点：', "RADIO3", key='location2', size=(12, 1)), sg.Input(key='location_input',visible=False)],

        ]
        layout4 = [[sg.Frame('交付时间及地点：', delivery_layout, title_color='red'), ]]
        file_layout=[[sg.Text('选择技术规格书', size=(15, 1)),sg.Input(key='file'),sg.FileBrowse(button_text='打开',file_types=(("Word Files", "*.docx"),))],
                     [sg.Button('生成合同')]]
        self.layout = layout1 + layout2 + layout3 + layout4 + file_layout

        self.root = sg.Window('自动生成工具', self.layout)

    def setdefault(self,arg):
        self.root['title'].Update(self.context['title'])
        if arg == 'payment4':
            self.root[21].Update('30%')
            self.root[22].Update('合同生效后一周内')
            self.root[23].Update('30%')
            self.root[24].Update('到货开箱并初步验收后30日内')
            self.root[25].Update('30%')
            self.root[26].Update('验收合格30日内')
            self.root[27].Update('10%')
            self.root[28].Update('质量保证期到期后30日内')
        elif arg == 'payment3':
            self.root[23].Update('60%')
            self.root[24].Update('验收合格30日内')
            self.root[25].Update('10%')
            self.root[26].Update('质量保证期到期后30日内')



if __name__ == '__main__':
    config = getConfig('config.ini',context_Hetong)
    window = GUI(context_Hetong)

    print(context_Hetong)
    while True:
        event, values = window.root.read()
        window.root.FindElement('title').Update(context_Hetong['title'])
        print(event, values)
        if event is None:
            break
        if event == 'hetong':
            for key in values.keys():
                context_Hetong.setdefault(key,values[key])
            print(context_Hetong)
            contract = Hetong(context_Hetong)
            contract.gethetong()

